package com.tds.springbootdemo2.util;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Copyright (C) 2014-2023 天津紫藤科技有限公司. Co. Ltd. All Rights Reserved.
 *
 * @author tongdashuai
 * @version 1.0
 * @description
 * @module
 * @date 2024/6/7 15:29
 */
@Component
public class RabbitUtil {

    @Autowired
    private  RabbitTemplate rabbitTemplate;


    /**
     * 发送延迟消息
     *
     * @param exchange 交换机名称
     * @param routingKey 路由名称
     * @param msg 消息内容
     * @param seconds 延迟时间，单位秒
     */
    public void sendDelayMessage(String exchange, String routingKey, String msg, int seconds)
    {
        //设置消息内容的类型，默认是 application/octet-stream 会是 ASCII 码值
        String s = routingKey + "-" + UUID.randomUUID();
        Message message = MessageBuilder.withBody(msg.getBytes())
                .setContentEncoding("utf-8")
                .setMessageId(s)
                .setHeader("x-delay", seconds * 1000)
                .build();
        rabbitTemplate.convertAndSend(exchange, routingKey, message, new CorrelationData(s));
    }
}
